package cn.ibdsr.human.util;

import cn.ibdsr.human.constant.BizConstants;
import org.springframework.util.StringUtils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

/**
 * 加密工具类
 * @author chenglx
 * @version V1.0
 * @date 2020/11/17 9:28
 * <p>
 * Date Author Description
 * ------------------------------------------------------
 * 2020/11/17 chenglx init
 */
public class EncryptionUtils {

    private static char[] charTable = "0123456789abcdef".toCharArray();
    private static int charCount = charTable.length;
    private static Random random = new Random();
    private static int defaultSaltLength = 16;


    /**
     * 产生随机的盐值
     * @param seed 种子字符串
     * @param length 生成的盐值长度
     * @return
     */
    public static String generateSalt(String seed, int length) {
        // 初始字符串检查
        if (StringUtils.isEmpty(seed)) {
            seed = "zoufang";
        }
        seed += System.nanoTime();
        byte[] seedBytes = seed.getBytes();
        // 长度检查
        if (length < 1) {
            length = defaultSaltLength;
        }
        // 生成随机字符串
        char[] salt = new char[length];
        for (int i = 0; i < length; ++i) {
            int idx = (random.nextInt(256) ^ seedBytes[random.nextInt(seedBytes.length)]) % charCount;
            salt[i] = charTable[idx];
        }
        return new String(salt);
    }

    /**
     * 根据默认配置生成盐值
     * @return
     */
    public static String generateSalt() {
        return generateSalt(null, BizConstants.SALT_LENGTH);
    }

    /**
     * 对输入的文本，按 SHA-256 计算其摘要
     * @param text
     * @return
     * @throws NoSuchAlgorithmException
     * @throws UnsupportedEncodingException
     */
    public static String digest(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        byte[] bytes = text.getBytes("UTF-8");
        return digest(bytes);
    }

    /**
     * 对输入的字节数组，按 SHA-256 计算其摘要
     * @param bytes
     * @return
     * @throws NoSuchAlgorithmException
     * @throws UnsupportedEncodingException
     */
    public static String digest(byte[] bytes) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        // todo 是否可以采用单例模式？
        MessageDigest digest = MessageDigest.getInstance(BizConstants.DIGEST_ALGORITHM);
        byte[] hash = digest.digest(bytes);
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < hash.length; ++i) {
            int v = hash[i] & 0xFF;
            if (v < 16) {
                builder.append("0");
            }
            builder.append(Integer.toString(v, 16));
        }
        return builder.toString();
    }


    public static void main(String[] args) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        System.out.println(EncryptionUtils.digest("abcd"));
    }

}
